package config

import (
	// "crypto/tls"
	"fmt"
	"log"
	"software/model"
	"time"
	"gopkg.in/gomail.v2"
	"gorm.io/gorm"
)

type EmailConfig struct {
	Host     string
	Port     int
	Username string
	Password string
	From     string
}

var EmailConf = &EmailConfig{
	Host:     "smtp.qq.com", // 使用QQ邮箱SMTP服务器
	Port:     587,
	Username: "2464200539@qq.com", 
	Password: "gajebmcpagxfdhie",  
	From:     "2464200539@qq.com", 
}

func SendVerificationCode(email string, code string) error {
	subject := "AI面试助手 - 验证码"
	body := fmt.Sprintf(`
		<html>
		<body>
			<h2>AI面试助手验证码</h2>
			<p>您的验证码是：<strong style="color: #5B6DFF; font-size: 24px;">%s</strong></p>
			<p>验证码有效期为5分钟，请尽快使用。</p>
			<p>如果这不是您的操作，请忽略此邮件。</p>
		</body>
		</html>
	`, code)

	m := gomail.NewMessage()
	m.SetHeader("From", EmailConf.From)
	m.SetHeader("To", email)
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", body)

	d := gomail.NewDialer(EmailConf.Host, EmailConf.Port, EmailConf.Username, EmailConf.Password)
	if err := d.DialAndSend(m); err != nil {
		log.Printf("Failed to send email: %v", err)
		return err
	}
	return nil
}

func SaveVerificationCode(db *gorm.DB, email, code string) error {
	// 删除旧的验证码
	db.Where("email = ?", email).Delete(&model.VerificationCode{})
	
	// 保存新的验证码
	verificationCode := &model.VerificationCode{
		Email:     email,
		Code:      code,
		ExpiresAt: time.Now().Add(5 * time.Minute), // 5分钟有效期
		Used:      false,
	}
	
	return db.Create(verificationCode).Error
}

func ValidateVerificationCode(db *gorm.DB, email, code string) (bool, error) {
	var verificationCode model.VerificationCode
	err := db.Where("email = ? AND code = ? AND used = ? AND expires_at > ?", 
		email, code, false, time.Now()).First(&verificationCode).Error
	
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return false, nil
		}
		return false, err
	}
	
	// 标记验证码为已使用
	db.Model(&verificationCode).Update("used", true)
	
	return true, nil
} 